package com.shuwen.gcdj.service.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.bean.VoidResp;
import com.shuwen.gcdj.bean.member.request.UserAddRemoveRoleReq;
import com.shuwen.gcdj.bean.role.response.RoleItemResp;
import com.shuwen.gcdj.bean.role.response.SuperRoleCacheResp;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.constant.MemberCst;
import com.shuwen.gcdj.common.constant.RolePowerCst;
import com.shuwen.gcdj.common.enums.ErrorCode;
import com.shuwen.gcdj.common.error.ErrorReport;
import com.shuwen.gcdj.common.util.account.AccountUtil;
import com.shuwen.gcdj.common.util.serialize.SerializeUtils;
import com.shuwen.gcdj.entity.AccountRole;
import com.shuwen.gcdj.entity.Role;
import com.shuwen.gcdj.mapper.mysql.AccountMapper;
import com.shuwen.gcdj.mapper.mysql.AccountRoleMapper;
import com.shuwen.gcdj.mapper.mysql.RoleMapper;
import com.shuwen.gcdj.service.BaseService;
import com.shuwen.gcdj.service.redis.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class AccountRoleService extends BaseService<AccountRoleMapper, AccountRole> {

    private final AccountRoleMapper accountRoleMapper;
    private final RoleMapper roleMapper;
    private final AccountMapper accountMapper;

    private final RedisService redisService;

    /**
     * 用户绑定/解绑某一角色
     *
     * @param req UserAddRemoveRoleReq
     * @return CommonResult<VoidResp>
     */
    public CommonResult<VoidResp> addRemoveRole(UserAddRemoveRoleReq req) {
        ErrorCode ck = checkAddRemoveRole(req);
        if (ErrorReport.hasError(ck)) {
            return CommonResult.failed(ck);
        }

        Integer opType = req.getOpType();
        if (opType.equals(Constants.FRP_AUTH_OP_TYPE_REMOVE)) {
            for (String accountId : req.getAccountId()) {
                removeAccountRole(accountId, req.getAuthType());
            }
            return CommonResult.success(new VoidResp());
        }

        for (String accountId : req.getAccountId()) {
            addAccountRole(accountId, req.getAuthType(), req.getLoginUserId());
        }
        return CommonResult.success(new VoidResp());
    }

    /**
     * 授权类型标识与角色code映射
     */
    private Map<Integer, String> getAuthTypeRoleCodeMap() {
        Map<Integer, String> resp = new HashMap<>();
        resp.put(Constants.FRP_AUTH_TYPE_ADMIN, RolePowerCst.ROLE_CODE_FRP_AUTH_ADMIN);
        resp.put(Constants.FRP_AUTH_TYPE_VIEW_ALL, RolePowerCst.ROLE_CODE_FRM_AUTH_VIEW_ALL);
        resp.put(Constants.FRP_AUTH_TYPE_VIEW_COMMON_SECRET, RolePowerCst.ROLE_CODE_FRM_AUTH_VIEW_COMMON_SECRET);
        resp.put(Constants.FRP_AUTH_TYPE_VIEW_COMMON_BUS, RolePowerCst.ROLE_CODE_FRM_AUTH_VIEW_COMMON_BUS);
        resp.put(Constants.RMP_LESSON_OWNER_ADMIN, RolePowerCst.ROLE_CODE_RMP_LESSON_OWNER_ADMIN);
        resp.put(Constants.RMP_LESSON_OWNER_VIEW, RolePowerCst.ROLE_CODE_RMP_LESSON_OWNER_VIEW);
        resp.put(Constants.RMP_LESSON_RECEIVE_APPLY_MSG, RolePowerCst.ROLE_CODE_RMP_LESSON_RECEIVE_APPLY_MSG);
        return resp;
    }

    /**
     * 为用户新增一个角色
     *
     * @param accountId   String
     * @param authType    Integer
     * @param loginUserId String
     */
    private void addAccountRole(String accountId, Integer authType, String loginUserId) {
        Map<Integer, String> mps = getAuthTypeRoleCodeMap();
        if (!mps.containsKey(authType)) {
            return;
        }

        // 先删除授权类型
        removeAccountRole(accountId, authType);

        // 绑定角色
        Role role = getRoleByRoleCode(mps.get(authType));
        if (role != null) {
            AccountRole accountRole = new AccountRole();
            accountRole.setAccountId(accountId);
            accountRole.setRoleId(role.getId());
            if (loginUserId != null) {
                accountRole.setCreateId(loginUserId);
                accountRole.setUpdateId(loginUserId);
            }
            save(accountRole);
        }

        // 更新用户缓存
        rebuildRolesCacheByUserId(accountId, isSuperUser(accountId));
    }

    /**
     * 判断用户是不是具有超级管理员权限
     *
     * @param userId String
     * @return boolean
     */
    public boolean isSuperUser(String userId) {
        List<RoleItemResp> rs = accountMapper.getRoles(userId, RolePowerCst.ROLE_CODE_SUPER);
        return rs != null && !rs.isEmpty();
    }

    /**
     * 获取普通管理员角色信息缓存 - 从DB获取
     */
    public List<RoleItemResp> getNormalRoles(String userId) {
        List<RoleItemResp> search = accountMapper.getRolesByUserId(userId, 0, RolePowerCst.getBizHiddenRoleCodes());
        if (search == null) {
            return new ArrayList<>();
        }
        return search;
    }

    /**
     * 获取超级管理员角色 - 从DB获取
     */
    public List<RoleItemResp> getSuperRoles() {
        List<RoleItemResp> search = accountMapper.getRolesByUserId(null, 1, null);
        if (search == null) {
            return new ArrayList<>();
        }
        return search;
    }

    /**
     * 重构用户角色缓存
     *
     * @param userId  String
     * @param isSuper boolean
     * @return List<RoleItemResp>
     */
    public List<RoleItemResp> rebuildRolesCacheByUserId(String userId, boolean isSuper) {
        String key = AccountUtil.buildUserRolesKey(userId);
        List<RoleItemResp> resp;
        if (isSuper) {
            resp = getSuperRoles();
        } else {
            resp = getNormalRoles(userId);
        }

        if (!resp.isEmpty()) {
            SuperRoleCacheResp cacheResp = new SuperRoleCacheResp();
            cacheResp.setItems(resp);
            redisService.setString(key, SerializeUtils.serialize(cacheResp), MemberCst.ACCOUNT_USER_ROLES_EXPIRE_SECONDS);
            return resp;
        }

        return new ArrayList<>();
    }

    /**
     * 解绑用户角色
     *
     * @param accountId String
     * @param authType  Integer
     */
    private void removeAccountRole(String accountId, Integer authType) {
        Map<Integer, String> mps = getAuthTypeRoleCodeMap();
        if (!mps.containsKey(authType)) {
            return;
        }

        String roleCode = mps.get(authType);
        AccountRole accountRole = getOneByRoleCode(accountId, roleCode);
        if (accountRole != null) {
            accountRoleMapper.deleteById(accountRole.getId());
        }

        // 更新用户缓存
        rebuildRolesCacheByUserId(accountId, isSuperUser(accountId));
    }

    private ErrorCode checkAddRemoveRole(UserAddRemoveRoleReq req) {
        if (req == null) {
            return ErrorCode.VALIDATE_FAILED;
        }

        if (req.getAccountId() == null || req.getAccountId().isEmpty()) {
            return ErrorCode.PARAM_LOST;
        }

        if (req.getOpType() == null) {
            return ErrorCode.PARAM_LOST;
        }

        if (req.getAuthType() == null) {
            return ErrorCode.PARAM_LOST;
        }

        return ErrorCode.SUCCESS;
    }

    public CommonResult<VoidResp> saveMulti(List<AccountRole> accountRoles) {
        if (saveBatch(accountRoles)) {
            log.info("AccountRoleService.saveMulti(accountRoles = {}) success", accountRoles);
            return CommonResult.success(new VoidResp());
        }

        log.error("error: AccountRoleService.saveMulti(accountRoles = {}) fail", accountRoles);
        return CommonResult.failed(ErrorCode.FAILED);
    }

    public List<String> getRoleIdsByUserId(String userId) {
        if (userId == null || userId.isEmpty()) {
            return new ArrayList<>();
        }

        QueryWrapper<AccountRole> qw = new QueryWrapper<>();
        qw.eq(Constants.FIELD_KEY_IS_DELETE, Constants.IS_DELETE_NORMAL);
        qw.eq("account_id", userId);
        List<AccountRole> lists = accountRoleMapper.selectList(qw);
        if (lists == null) {
            return new ArrayList<>();
        }

        List<String> resp = new ArrayList<>();
        Map<String, Boolean> maps = new HashMap<>();
        for (AccountRole v : lists) {
            if (!maps.containsKey(v.getRoleId())) {
                resp.add(v.getRoleId());
                maps.put(v.getRoleId(), true);
            }
        }
        return resp;
    }

    public AccountRole getOneByRoleCode(String accountId, String roleCode) {
        Role role = getRoleByRoleCode(roleCode);
        if (role == null) {
            return null;
        }

        QueryWrapper<AccountRole> qw = new QueryWrapper<>();
        qw.eq("`role_id`", role.getId());
        qw.eq("`account_id`", accountId);
        qw.last("limit 1");
        return accountRoleMapper.selectOne(qw);
    }

    private Role getRoleByRoleCode(String roleCode) {
        QueryWrapper<Role> q = new QueryWrapper<>();
        q.eq("`code`", roleCode);
        q.last("limit 1");
        return roleMapper.selectOne(q);
    }
}
